-- SkyScrapBonusM
-- Created by huanghr
-- 谜の雕像奖励

module("SkyScrapBonusM", package.seeall);

-- 天赋图标配置信息
local skyScrapBonusTable = {};
local SKY_SCRAP_ID = 10001;


-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    local sky_scrap_bonus_CSV = get_sky_scrap_bonus_CSV();
    for i = 1, #sky_scrap_bonus_CSV do
        local id = sky_scrap_bonus_CSV[i].id;
        skyScrapBonusTable[id] = parseRow(sky_scrap_bonus_CSV[i]);
    end

    sky_scrap_bonus_CSV = {};
end

-- 初始化
function init()
    loadCsv();
end

-- 解析奖励信息
function parseBonus(bonus)
    local arr = string.explode(bonus, "+");
    local bonusList = {};
    local temp;
    for _, str in pairs(arr) do
        if str ~= "" then
            if string.startWith(str, "1(") and string.endWith(str, ")") then
                -- 物品奖励
                temp = string.explode(string.sub(str, 3, -2), ",");
                table.insert(bonusList, {1, tonumber(temp[1]), tonumber(temp[2]) });
            elseif string.startWith(str, "2(") and string.endWith(str, ")") then
                -- 属性奖励
                temp = string.explode(string.sub(str, 3, -2), ",");
                table.insert(bonusList, {2, temp[1], tonumber(temp[2]) });
            elseif string.startWith(str, "3(") and string.endWith(str, ")") then
                -- 冈布奥奖励
                temp = string.explode(string.sub(str, 3, -2), ",");
                table.insert(bonusList, {3, tonumber(temp[1]), tonumber(temp[2]) });
            elseif string.startWith(str, "8(") and string.endWith(str, ")") then
                -- 机器人奖励
                temp = string.explode(string.sub(str, 3, -2), ",");
                table.insert(bonusList, {8, tonumber(temp[1]), tonumber(temp[2]) });
            else
                assert(false, "奖励类型配置错误");
            end
        end
    end
    return bonusList;
end

-- 解析行
function parseRow(row)
    row["bonus"] = parseBonus(row["bonus"]);
    row["bakup_bonus"] = parseBonus(row["bakup_bonus"]);
    return row;
end

-- 检索奖励信息
function query(id, path)
    local m = skyScrapBonusTable[id]

    if not m or path == "" or not path then
        return m
    end

    return m[path]
end

-- 获取所有奖励
function getAllBonusConfig()
    return skyScrapBonusTable;
end

-- 奖励是否已领取
function isTaken(id)
    local curId = ME.user.dbase:query("sky_scrap_progress", 0);
    return id <= curId;
end

-- 奖励是否可领取(id)
function canBeTaken(id)
    -- 荣誉勋章
    local requireNum = query(id, "amount");
    if requireNum == nil then
        return false;
    end

    -- 荣誉勋章数量
    local currentNum = ItemM.getAmount(ME.user, SKY_SCRAP_ID);
    if (currentNum < requireNum) then
        return false;
    end

    return true;
end

-- 获得最终奖励
function getFinalBonus(user, id)
    local bonusList = query(id, "bonus");
    for _, bonus in pairs(bonusList) do
        if bonus and bonus[1] == 1 then
            local itemId = bonus[2];
            if ItemM.query(itemId, "type") == ITEM_TYPE_ARTIFACT then
                -- 已有神器并且领取的是神器碎片, 使用备选奖励
                if not isTaken(id) and ItemM.getAmount(user, itemId) > 0 then
                    return query(id, "bakup_bonus");
                elseif isTakenBackupBonus(id) then
                    return query(id, "bakup_bonus");
                end
            end
        end
    end

    return bonusList;
end

-- 领取奖励
function takeBonus()
    -- 未领取的奖励ID
    local id = ME.user.dbase:query("sky_scrap_progress", 0) + 1;

    -- 判断需要的世界树果实数量是否足够
    local requireNum = query(id, "amount");
    if requireNum == nil then
       return "all_taken";
    end

    -- 荣誉勋章数量
    local currentNum = ItemM.getAmount(ME.user, SKY_SCRAP_ID);
    if (currentNum < requireNum) then
        return "item_lack";
    end

    -- 给玩家奖励
    local bonusList = getFinalBonus(ME.user, id);
    if bonusList == nil then
        return false;
    end

    for _, bonus in pairs(bonusList) do
        BonusM.doBonus(bonus, "sky_scrap_bonus");

        -- 神器碎片，记录是备用奖励
        if bonus and bonus[1] == 1 then
            local itemId = bonus[2];
            if ItemM.query(itemId, "type") == ITEM_TYPE_ARTIFACT_SCRAP then
                setTakenBackupBonus(id)
            end
        end
    end

    -- 设置领取进度
    ME.user.dbase:set("sky_scrap_progress", id);

    -- 抛出领取奖励事件
    EventMgr.fire(event.TAKE_FRUIT_BONUS, { ["bonusList"] = bonusList, });
    return true;
end

-- 获取可领取的奖励个数
function getAvailableBonuNum()
    local num = 0;

    local bonusList = getAllBonusConfig();
    for id, _ in pairs(bonusList) do
        local canBeTaken = canBeTaken(id);
        local isTake = isTaken(id);
        if canBeTaken and not isTake then
            num = num + 1;
        end
    end
    return num;
end

-- 设置领取的备用奖励
function setTakenBackupBonus(id)
    local takenBackupBonus = ME.user.dbase:query("ss_backup_bonus", {});

    local index = id;

    local m = takenBackupBonus[index];
    if m == nil then
        return;
    end

    if m.state == 0 then
        m.state = 1;

        takenBackupBonus[index] = m;
        ME.user.dbase:set("ss_backup_bonus", takenBackupBonus);
    end
end

-- 获取当前奖励是否时备用奖励
function isTakenBackupBonus(id)
    local takenBackupBonus = ME.user.dbase:query("ss_backup_bonus", {});

    local index = id;

    local m = takenBackupBonus[id];
    if m == nil then
        return false;
    end

    if m.state == 0 then
        return false;
    end

    return true;
end